﻿using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IPC.Client
{
    public class NamedPipeClient
    {
        public NamedPipeClientStream pipeClient;
        StreamReader sr;
        StreamWriter sw;

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="pipename"></param>
        /// <returns></returns>
        public NamedPipeClientStream CreatPipeClient(string pipename)
        {
            pipeClient = new NamedPipeClientStream(".", pipename);
            sr = new StreamReader(pipeClient);
            sw = new StreamWriter(pipeClient);
            return pipeClient;
        }


        /// <summary>
        /// 接收
        /// </summary>
        /// <returns></returns>
        public string Receive()
        {
            string str = "";
            try
            {
                //str = pipeClient.ReadByte().ToString();

                str = sr.ReadLine();

                //byte[] buffff = new byte[8];
                //pipeClient.Read(buffff, 0, 8);
                //str = buffff[0].ToString();
            }
            catch (Exception ex)
            {

            }
            return str;
        }


        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="command"></param>
        public void Send(byte command)
        {
            try
            {
                pipeClient.WriteByte(command);
                pipeClient.Flush();

                //sw.WriteLine(command);
                //sw.Flush();

                //byte[] buffff = new byte[2];
                //buffff[0] = command;
                //pipeClient.Write(buffff, 0, 2);
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="command"></param>
        public void Send(string command)
        {
            try
            {
                //pipeClient.WriteByte(command);
                //pipeClient.Flush();

                sw.WriteLine(command);
                sw.Flush();

                //byte[] buffff = new byte[2];
                //buffff[0] = command;
                //pipeClient.Write(buffff, 0, 2);
            }
            catch (Exception ex)
            {

            }
        }
    }
}
